
package de.ars.client.items;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;


import de.ars.client.animator.Animator;
import de.ars.client.animator.IAnimationEventListener;
import de.ars.client.animator.Point;
import de.ars.client.camera.imageProcessor;
import de.ars.client.datahandling.InformationGroup;
import de.ars.client.datahandling.InformationItem;
import de.ars.client.datahandling.Person;
import de.ars.client.datahandling.PropertyReader;
import de.ars.client.items.animators.OverViewItemAnimator;
import de.ars.client.items.elements.AbstractItem;
import de.ars.client.items.elements.ChooseItem;
import de.ars.client.items.elements.ListItem;
import de.ars.client.items.elements.StarItem;
import de.ars.client.items.elements.StarItemListener;
import de.ars.client.paintSystems.ClassicLayout;
import de.ars.client.paintSystems.StringPainter;
import de.ars.client.screens.MainScreen;
import de.ars.client.tools.Factory;
import de.ars.common.IDataModelConstants;
import de.ars.common.ISharedResources;

public class OverViewItem implements IAnimationEventListener, StarItemListener
{
    private static final int COLOR_BORDER = 0x0010475f;
    private static final int COLOR_WINDOW_BACKGROUND = 0x0025afd4;

    public static final int ANIMATION_SWITCH_DETAIL_NORMAL = 0;
    public static final int ANIMATION_MOVE_RIGHT = 1;
    public static final int ANIMATION_MOVE_LEFT = 2;
    public static final int ANIMATION_SCROLL_UP = 3;
    public static final int ANIMATION_SCROLL_DOWN = 4;
    public static final int ANIMATION_OPEN_SETTINGS = 5;

    public static final int VERTICAL_STEPS = 5;
	private OverViewItemAnimator animator = null;

    private Image img = ISharedResources.IMAGE_UNKOWN_WOMEN;

    private boolean isInDetailView = false;

    private int relativPos = 0; 

    private Person person = null;

    private int animationType = -1;

    StringPainter stringPainter = null;
    private int verticalViewPos = 0;

    private Vector items;
    private int selectedItemIndex = 0;
    
    private ClassicLayout layout;
    private MainScreen main;
    
    private IOverViewItemEventListener listener;

    public OverViewItem( int relativePos, StringPainter stringPainter,ClassicLayout _layout, MainScreen mainScreen )
    {
        this.stringPainter = stringPainter;
        this.layout = _layout;
        this.layout.recalcImagePos(img.getWidth(),img.getHeight());
        this.animator = new OverViewItemAnimator( this );

        animator.createNewAnimationPoint( layout.getPos( relativePos ) );
        animator.createNewAnimationPoint( layout.getSize( relativePos ) );
        animator.createNewAnimationPoint( layout.getPortraitPos( relativePos ) );
        animator.createNewAnimationPoint( layout.getTextPos( relativePos ) );
        animator.setLayout( this.layout );

        this.relativPos = relativePos;

        this.main = mainScreen;
        
        this.items = new Vector();
    }
    
    public void setListener(IOverViewItemEventListener _listener)
    {
    	this.listener = _listener;
    }

    public void paint( Graphics g )
    {
    	
    	if( this.person != null && relativPos >= -2 && relativPos <= 2 )
        {
            Point pos = animator.getPoint( OverViewItemAnimator.POINT_WINDOW_POS );
            Point size = animator.getPoint( OverViewItemAnimator.POINT_WINDOW_SIZE );
            Point portraitPos = animator.getPoint( OverViewItemAnimator.POINT_PORTRAIT_POS );
            Point textPos = animator.getPoint( OverViewItemAnimator.POINT_TEXT_POS );
            textPos.setBoth( pos.getX() + textPos.getX(), pos.getY() + textPos.getY() );

            if( this.isInDetailView )
            {
                portraitPos.setY( portraitPos.getY() - verticalViewPos );
                textPos.setY( textPos.getY() - verticalViewPos );
            }

            g.setColor( COLOR_WINDOW_BACKGROUND );
            g.fillRect( (int)pos.getX() + main.DEBUG_viewPos, (int)pos.getY(), (int)size.getX(), (int)size.getY() );
            g.setColor( COLOR_BORDER );
            g.drawRect( (int)pos.getX() + main.DEBUG_viewPos, (int)pos.getY(), (int)size.getX(), (int)size.getY() );

            //drawDebugItems(g, textPos );
            if( relativPos >= -1 && relativPos <= 1 )
            {
                g.drawImage( img, (int)(pos.getX() + portraitPos.getX() - (img.getWidth()/2)), (int)(pos.getY() + portraitPos.getY()),
                        Graphics.TOP | Graphics.LEFT );
                if( this.isInDetailView && relativPos == 0 && this.animationType != ANIMATION_SWITCH_DETAIL_NORMAL )
                    drawDetailItems( g, textPos );
                else
                    drawNormalItems( g, textPos );
            }
        }
    }
    
    private void drawDetailItems( Graphics g, Point pos )
    {
    	AbstractItem currentItem = null;
        int y = (int)pos.getY();
        int x = (int)pos.getX();
        int i = 0;
        Enumeration e = this.items.elements();
        while( e.hasMoreElements())
        {
            g.translate( x - g.getTranslateX(), y - g.getTranslateY() );
            currentItem = (AbstractItem)e.nextElement();
            currentItem.paint( g, i== this.selectedItemIndex);//, this.main.getEditItemStatus());
            y += currentItem.getHeight();
            i++;
        }
    }

    private void drawNormalItems( Graphics g, Point pos )
    {
        int y = (int)pos.getY();
        int x = (int)pos.getX();
        g.translate( x - g.getTranslateX() + main.DEBUG_viewPos, y - g.getTranslateY() );
        ((AbstractItem)this.items.elementAt( 0 )).paint( g,selectedItemIndex==0);//, false );
        g.translate( x - g.getTranslateX() + main.DEBUG_viewPos, y - g.getTranslateY() + ((AbstractItem)this.items.elementAt( 0 )).getHeight() );
        ((AbstractItem)this.items.elementAt( 1 )).paint( g,false);//, false );
    }
    
    public AbstractItem getItemAtIndex(int _index)
    {
    	return ((AbstractItem)this.items.elementAt(_index));
    }

    public void setImage( Image img )
    {
        this.img = img;
        this.layout.recalcImagePos(this.img.getWidth(), this.img.getHeight());
    }

    public void process( long elapsed )
    {
        animator.process( elapsed );
    }

    public void keyPressed( int keyCode )
    {
    	if (animationType == -1)
    	{
    		
        if( this.person != null )
            switch( keyCode )
            {
                case -3: //Left Arrow
                	if (main.overViewItem[2].getPerson().getPrev() != null && !main.overViewItem[2].isInDetailView())
                		if( relativPos + 1 < 3 )
	                	{
	                		this.animationType = ANIMATION_MOVE_RIGHT;
	                        animator.animateTo( relativPos + 1 );
	                	}
//                	if (this.isInDetailView)
//                    	((AbstractItem)items.elementAt(selectedItemIndex)).keyPressed(keyCode);
                break;
                case -4: //Right Arrow
                	if (main.overViewItem[2].getPerson().getNext() != null && !main.overViewItem[2].isInDetailView())
	                	if( relativPos - 1 > -3)
	                	{
	                		this.animationType = ANIMATION_MOVE_LEFT;
	                		animator.animateTo( relativPos - 1);
	                	}
//                	if (this.isInDetailView)
//                    	((AbstractItem)items.elementAt(selectedItemIndex)).keyPressed(keyCode);
                break;
                case -5: //Fire Button
                    if( this.person != null )
                    {
                        verticalViewPos = 0;
                        trySwitchDetailNormal();
                    }
                    break;
                case -2:
                    if( isInDetailView && this.relativPos == 0 && this.selectedItemIndex < this.items.size()-1)
                    {
                        this.animationType = ANIMATION_SCROLL_DOWN;
                        animator.animateScrollDown(((AbstractItem)this.items.elementAt( this.selectedItemIndex )).getHeight());
                    }
                    break;
                case -1:
                    if( isInDetailView && this.relativPos == 0 && this.selectedItemIndex > 0)
                    {
                        this.animationType = ANIMATION_SCROLL_UP;
                        animator.animateScrollUp(((AbstractItem)this.items.elementAt( this.selectedItemIndex-1 )).getHeight());
                    }
                    break;
            }
    	}
    }

    private void trySwitchDetailNormal()
    {
        selectedItemIndex = 0;        
        switch( this.relativPos )
        {
            case 0:
            	if( isInDetailView )
            		animator.shrinkToNormal( relativPos );
            	else
            		animator.growToDetail();
                this.animationType = ANIMATION_SWITCH_DETAIL_NORMAL;
                break;
            case -1:
            	if( isInDetailView )
            		animator.shrinkToNormal( relativPos );
            	else
            		animator.animateTo( relativPos - 1 );
                this.animationType = ANIMATION_SWITCH_DETAIL_NORMAL;
                break;
            case 1:
            	if( isInDetailView )
            		animator.shrinkToNormal( relativPos );
            	else
            		animator.animateTo( relativPos + 1 );
                this.animationType = ANIMATION_SWITCH_DETAIL_NORMAL;
                break;
        }
        
        this.isInDetailView = !this.isInDetailView;
    }

    public void setPerson( Person person )
    {
        this.person = person;
        this.items = new Vector();
        try
        {
            if( this.person != null )
            {
                /*String path = person.getInformation( IDataModelConstants.PERSON_PORTRAIT_PATH );
                if( path != null )
                    img = Image.createImage( path );*/
                this.updateItems();
            }
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }
    }

    public Person getPerson()
    {
        return this.person;
    }
    
    public int getSelectedIndex()
    {
    	return this.selectedItemIndex;
    }
    
    public AbstractItem getSelectedItem()
    {
    	return this.getItemAtIndex(this.selectedItemIndex);
    }
    
    public boolean getDetailStatus()
    {
    	return this.isInDetailView;
    }

    public void animationEvent( int event )
    {
    	if( event == IAnimationEventListener.ANIMATION_STARTED )
        {
    		switch( this.animationType )
            {
            case ANIMATION_MOVE_LEFT:
            	this.listener.overViewItemActionPerformed(IOverViewItemEventListener.SCROLING_LEFT_STARTED);
                break;
            case ANIMATION_MOVE_RIGHT:
            	this.listener.overViewItemActionPerformed(IOverViewItemEventListener.SCROLING_RIGHT_STARTED);
                break;
            }
        }else if( event == IAnimationEventListener.ANIMATION_STOPPED )
        {
            switch( this.animationType )
            {
                case ANIMATION_SWITCH_DETAIL_NORMAL:
                    this.animator.resetPosition( true );
                    break;
                case ANIMATION_MOVE_LEFT:
                	this.animator.resetPosition( false );
                	this.listener.overViewItemActionPerformed(IOverViewItemEventListener.SCROLING_LEFT_STOPPED);
                    break;
                case ANIMATION_MOVE_RIGHT:
                	this.animator.resetPosition( false );
                	this.listener.overViewItemActionPerformed(IOverViewItemEventListener.SCROLING_RIGHT_STOPPED);
                    break;
                case ANIMATION_SCROLL_DOWN:
                    this.animator.resetPosition( true );
                    this.selectedItemIndex++;
                    break;
                case ANIMATION_SCROLL_UP:
                    this.animator.resetPosition( true );
                    this.selectedItemIndex--;
                    break;
            }
            this.animationType = -1;
        }
    }
    
    public Enumeration getInformations()
    {
    	return this.person.getInformationEnumeration();
    }
    
    public void updateOverAllStarItemValue()
    {
    	int valueSum = 0;
    	int valueCount = 0;
    	AbstractItem currentItem;
    	for (int i = 2; i < this.items.size();i++)
    	{
    		currentItem = (AbstractItem)this.items.elementAt(i);
            String key = currentItem.getKey();
            String group = key.substring( 0 , key.indexOf('.') );
            String valueKey = key.substring( key.indexOf('.') +  1 );
            
            
            InformationGroup tempInfoGroup = (InformationGroup)main.getInformationGroup().get(group);
	        InformationItem tempInfoItem = tempInfoGroup.getItem(valueKey);
	        if (tempInfoItem != null)
	        {
	          if (tempInfoItem.GetTyp().equals(InformationItem.TYP_STARS))
	          {
	        	  System.out.println(((StarItem)currentItem).getValue());
	        	  valueSum += Integer.parseInt(((StarItem)currentItem).getValue());
	        	  valueCount++;
	          }
	        }
        } 
        if (valueCount > 0)
        	((StarItem)this.items.elementAt(1)).setValue(valueSum/valueCount);
    }

    public void updateItems()
    {
        this.items = new Vector();
        String key = null;
        String value = null;
        String propertyValue = null;
        ListItem tempItem = new ListItem( this.stringPainter, this.person.getInformation( "person.firstname" ) + ' '
                + this.person.getInformation( "person.lastname" ) );
        tempItem.shownInNormalView = true;
        this.items.addElement( tempItem );

        if (this.person.getInformation("person.portrait_path") != null)
        {
        	img = Factory.createImageFromFileSystem(this.person.getInformation("person.portrait_path"));
        	if (img == null)
        		img = ISharedResources.IMAGE_UNKOWN_WOMEN;
        	else
        		img = imageProcessor.resizeImage(img,89,111);
        }	
        else
        	img = ISharedResources.IMAGE_UNKOWN_WOMEN;
        
        this.items.addElement( new StarItem( "", "0", false) );
        Enumeration e = this.person.getInformationEnumeration();
        while( e.hasMoreElements() )
        {
            key = (String)e.nextElement();
            String group = key.substring( 0 , key.indexOf('.') );
            String valueKey = key.substring( key.indexOf('.') +  1 );
            
            value = this.getPerson().getInformation( key );
          
            InformationGroup tempInfoGroup = (InformationGroup)main.getInformationGroup().get(group);
            InformationItem tempInfoItem = tempInfoGroup.getItem(valueKey);
            if (tempInfoItem != null)
            {
	            if (tempInfoItem.GetTyp().equals(InformationItem.TYP_CHOOSE))
	            {
		            propertyValue = PropertyReader.getProperty( "label." + value );
		            if( propertyValue != null )
		                value = propertyValue;
		            ChooseItem tempChooseItem = new ChooseItem(this.stringPainter,PropertyReader.getProperty( "label." + key ) + ": ",key,tempInfoItem.getOptions());
		            this.items.addElement(tempChooseItem);
	            }
	            else if (tempInfoItem.GetTyp().equals(InformationItem.TYP_TEXT))
	            {
	            	this.items.addElement( new ListItem( this.stringPainter, PropertyReader.getProperty( "label." + key ) + ": ", value, key ) );
	            }
	            else if (tempInfoItem.GetTyp().equals(InformationItem.TYP_DIGIT))
	            {
	            	this.items.addElement( new ListItem( this.stringPainter, PropertyReader.getProperty( "label." + key ) + ": ", value, key ) );
	            }
	            else if (tempInfoItem.GetTyp().equals(InformationItem.TYP_STARS))
	            {
	            	StarItem tempStarItem = new StarItem( PropertyReader.getProperty( "label." + key ) + ": ",value ,true);
	            	tempStarItem.setKey(key);
	            	tempStarItem.setListener(this);
	            	this.items.addElement( tempStarItem );	
	            	updateOverAllStarItemValue();
	            }
	            else if (tempInfoItem.GetTyp().equals(InformationItem.TYP_DATE))
	            {
	            	
	            }	            
            }
        }
    }

    public boolean isAnimationInProgress()
    {
        return animator.getAnimationState() == Animator.ANIMATION_IN_PROGRESS;
    }
    
    public boolean isInDetailView()
    {
    	return isInDetailView;
    }
    
    public void valueChanged()
    {
    	updateOverAllStarItemValue();
    }
}
